package org.andao.core.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http servlet工具类型，如获取IP,host等信息
 * @author Marco.hu(hzg139@163.com)
 *
 */
public final class HttpServletUtils {

	protected static Logger logger = LoggerFactory.getLogger(HttpServletUtils.class);
	
	/**
	 * 获取客户端IP地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
	

	/**
	 * 绕过JSP直接输出，用于如AJAX等请求的情况。
	 * eg.
	 * render("text/plain", "hello", "encoding:GBK");
	 * render("text/plain", "hello", "no-cache:false");
	 * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
	 * @param contentType
	 * @param content
	 * @param headers 可变的header数组，目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true.
	 */
	public static void render(HttpServletResponse response,final String contentType, String content, final String... headers) {
		try {
			//分析headers参数
			String encoding = "UTF-8";
			boolean noCache = true;
			for (String header : headers) {
				String headerName = ExStringUtils.substringBefore(header, ":");
				String headerValue = ExStringUtils.substringAfter(header, ":");

				if (ExStringUtils.equalsIgnoreCase(headerName, "encoding")) {
					encoding = headerValue;
				} else if (ExStringUtils.equalsIgnoreCase(headerName, "no-cache")) {
					noCache = Boolean.parseBoolean(headerValue);
				} else
					throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
			}		

			//设置headers参数
			String fullContentType = contentType + ";charset=" + encoding;
			response.setContentType(fullContentType);
			if (noCache) {				
				response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");   
				response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
				response.setHeader("Pragma", "No-cache");				
				response.setDateHeader("Expires", 0);
			}

			response.getWriter().write(content);
			response.getWriter().flush();
			
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}finally{
			try {
				content = null;
				response.getWriter().close();
			} catch (IOException e) {
				logger.error("绕过JSP直接输出，用于如AJAX等请求的情况关闭PrintWriter出错:{}"+e.fillInStackTrace());
			}
		}
	}
	
	
}
